package com.yzc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yzc.execption.ZcException;
import com.yzc.mapper.UserMapper;
import com.yzc.model.entity.system.SysUser;
import com.yzc.result.Result;
import com.yzc.result.ResultCodeEnum;
import com.yzc.util.BCrypt;
import com.yzc.util.JwtUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private BCrypt passwordEncoder;

    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        // 1. 防御用户枚举攻击：无论用户是否存在，均模拟密码验证
        SysUser user = userMapper.selectOne(new QueryWrapper<SysUser>()
                .eq("name", request.getName()));
        if (user == null) {
            passwordEncoder.matches(request.getPass(), "dummyHash");
            throw new ZcException(ResultCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        // 2. 验证密码
        if (!passwordEncoder.matches(request.getPass(), user.getPassword())) {
            throw new ZcException(ResultCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        // 3. 生成Token（确保单点登录）
        String token = jwtUtil.generateToken(user);
        String redisKey = String.format("user:token:%s", user.getId());

        // 4. 存储到Redis（与JWT过期时间一致）
        redisTemplate.opsForValue().set(
                redisKey,
                token,
                jwtUtil.getExpirationMillis(),  // jwt中设置的过期时间
                TimeUnit.MILLISECONDS           //时间单位为毫秒
        );

        // 5. 记录登录日志
        log.info("用户登录成功: userId={}, username={}", user.getId(), user.getUsername());

        // 6. 返回响应（隐藏敏感信息）
        return Result.success(new LoginResponse(
                token,
                user.getId(),
                user.getUsername(),
                user.getEmail()
        ));
    }

    @PostMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String authHeader) {
        // 1. 提取并验证Token格式
        String token = jwtUtil.resolveToken(authHeader);
        if (token == null) {
            throw new ZcException(ResultCodeEnum.INVALID_TOKEN);
        }

        // 2. 解析用户ID
        Long userId = jwtUtil.extractUserId(token);

        // 3. 删除Redis中的Token
        String redisKey = String.format("user:token:%s", userId);
        Boolean deleted = redisTemplate.delete(redisKey);
        if (Boolean.TRUE.equals(deleted)) {
            log.info("用户退出登录: userId={}", userId);
        }

        return Result.success();
    }

    // 请求/响应对象
    @Data
    static class LoginRequest {
        @NotBlank(message = "用户名不能为空")
        private String name;
        @NotBlank(message = "密码不能为空")
        private String pass;
    }

    @Data
    @AllArgsConstructor
    static class LoginResponse {
        private String token;
        private Long userId;
        private String name;
        private String email;
    }
}
